
package com.probiz.estore.sales.dao.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.Assert;

import com.probiz.estore.common.model.sales.GiftCertificate;
import com.probiz.estore.core.dao.impl.HibernateGenericDaoImpl;
import com.probiz.estore.core.search.SearchCriteria;
import com.probiz.estore.core.util.HibernateUtils;
import com.probiz.estore.sales.dao.GiftCertificateDao;
import com.probiz.estore.sales.model.GiftCertificateSearchCriteria;

/**
 * GiftCertificate Data Access Object (DAO) implementation. Developer introduced
 * interfaces should be declared here. Won't get overwritten.
 */
public class GiftCertificateDaoImpl extends
		HibernateGenericDaoImpl<GiftCertificate> implements GiftCertificateDao {

	public GiftCertificate getGiftCertificate(String giftCertificateNo) {
		List list = getHibernateTemplate().find("from GiftCertificate gc where gc.giftCertificateNo='" + StringEscapeUtils.escapeSql(giftCertificateNo) + "'");
		if (list.size() == 0) {
			return null;
		}

		return (GiftCertificate) list.get(0);
	}

	public List<GiftCertificate> searchGiftCertificates(SearchCriteria _searchCriteria, GiftCertificateSearchCriteria _giftCertificateSearchCriteria) {
		SearchCriteria searchCriteria = _searchCriteria;
		GiftCertificateSearchCriteria giftCertificateSearchCriteria = _giftCertificateSearchCriteria;
		if(!_searchCriteria.isLastSearchCriteriaUsed()){
			List<Object> paramList = new ArrayList<Object>();
			StringBuffer sb = new StringBuffer();
			if (null != giftCertificateSearchCriteria.getState()) {
				String format = "yyyy-MM-dd";
				SimpleDateFormat dateFormat = new SimpleDateFormat(format);
				String now = dateFormat.format(new Date());
	
				if (GiftCertificate.SA_STATE_PAST.equals(giftCertificateSearchCriteria.getState())) {
					sb.append(" ( expireTime is not null and '" + now + "' >= expireTime )");
					paramList.add(now);
				} else {
					sb.append(" ( expireTime is  null or '" + now + "' < expireTime )");
					sb.append(" and status = " + giftCertificateSearchCriteria.getState().shortValue());
					paramList.add(now);
				}
			}
			if(StringUtils.isNotBlank(sb.toString())){
				searchCriteria.setHql(HibernateUtils.appendWhereAndClauseToHql(searchCriteria.getHql(), "and", sb.toString()));
				for (Object object : paramList) {
					searchCriteria.addParamValue(object);
				}
			}
		}
		List<GiftCertificate> list = searchByCriteria(searchCriteria);
		return list;

	}

	public boolean existGiftCertificateNo(String giftCertificateNo) {
		List<GiftCertificate> list = getHibernateTemplate().find(
				"from GiftCertificate gc where gc.giftCertificateNo='" + StringEscapeUtils.escapeSql(giftCertificateNo) + "'");
		return (list.size() != 0) ? true : false;
	}

}